#!/usr/bin/env python3
# coding=utf-8

import os
from .jar_dependency import *
from .stat import *

__all__=['JarDependency', 'JarDependencyParser','DependencySqlBuilder','UncoverJar','dependency_parse','uncover_jar','extract_dependency']

def dependency_parse(dependencyTreeDir, dbFromId, extend='.txt'):
    parser = JarDependencyParser()
    sqldir = os.path.relpath(os.path.join(dependencyTreeDir, '../sql'))
    if not os.path.exists(sqldir):
        os.mkdir(sqldir)
    for filename in os.listdir(dependencyTreeDir):
        if os.path.splitext(filename)[-1] != extend:
            continue
        sqlfilename = os.path.join(sqldir , filename.replace(os.path.splitext(filename)[-1],'.sql'))
        treeRoot = parser.parse(os.path.join(dependencyTreeDir, filename))
        builder = DependencySqlBuilder(treeRoot, sqlfilename)
        builder.init_id(treeRoot, dbFromId)
        builder.build()
        print('[INFO]', os.path.relpath(os.path.join(dependencyTreeDir, filename)), ' parse completed, sql file is ', sqlfilename)
        dbFromId += 1000
def uncover_jar(baseDir, targetDir):
    uncover = UncoverJar(baseDir, targetDir)
    lst = uncover.diff()
    return lst
def extract_dependency(dependencyTreeDir, extend='.txt'):
    for filename in os.listdir(dependencyTreeDir):
        if os.path.splitext(filename)[-1] != extend:
            continue
        extract = []
        matched = False
        filename = os.path.join(dependencyTreeDir, filename)
        with open(filename, 'rt', encoding='utf-8') as f:
            for line in f.readlines():
                if line.startswith('[INFO] --- maven-dependency-plugin'):
                    matched = True
                    continue
                if matched:
                    if line.startswith('[INFO] -----------'):
                        break
                    else:
                        extract.append(line.replace('[INFO] ',''))
        if matched and extract:
            os.system('cp ' + filename + ' ' + filename + '.bak')
            with open(filename, 'wt', encoding='utf-8') as f:
                f.writelines(extract)